/*
 * License:
 * =============================================================================
 * Copyright 2007  PANEL Martin
 * email : xxorax@gmail.com
 * website : http://www.xorax.info
 * 
 * This work is licensed under a Creative Commons Attribution-Share Alike 3.0
 * License (http://creativecommons.org/licenses/by-sa/3.0/)
*/

//my cool function ;)
//ref: http://www.xorax.info/blog/news/159-javascript-eval-global-scope.html
var globaleval =  function(script){
	if(window.execScript){
		return window.execScript(script);
	} else if(navigator.userAgent.indexOf('KHTML') != -1){ //safari, konqueror..
			var s = document.createElement('script');
			s.type = 'text/javascript';
			s.innerHTML = script;
			document.getElementsByTagName('head')[0].appendChild(s);
	} else {
		return window.eval(script);
	}
}

Ajax.savedForm = false;

Ajax.Responders.register({
	onCreate: function(th){
		if(Ajax.savedForm){
			th.options.savedForm = Ajax.savedForm;
		}
	},
	
  onComplete: function(th, xhr) {
		//$('info').innerHTML += 'complete<br/>';
		var oldActiveXHR = Ajax.activeRequestCount;
		
		if(th.options.savedForm){
			Ajax.savedForm = th.options.savedForm;
		}
		
   	try{
   	var fieldname = false;
    var update = [];
   	$A(xhr.responseXML.getElementsByTagName('item')).each(function(item){
   		fieldname = false;
   		$A(item.childNodes).each(function(p){
   			if(!p.firstChild || !p.firstChild.nodeValue) return;
   			var c = p.firstChild;
   			if(!fieldname && p.tagName == 'field' && c.nodeType == 3){
   				fieldname = p.firstChild.nodeValue;
   			}else if(fieldname && p.nodeType == 1 && (c.nodeType==3 || c.nodeType==4)){
   				switch(p.tagName){
   				case 'head':
   				case 'foot':
   					Element.update(fieldname+'--'+p.tagName,p.firstChild.nodeValue);
   					//new Effect.Highlight(fieldname+'--'+p.tagName,{duration: 1, startcolor:"#AA0300"});
            update.push([fieldname+'--'+p.tagName,"#AA0300"]);
   				break;
   				case 'reload':
   					Element.update(fieldname+'--content',p.firstChild.nodeValue);
   					//new Effect.Highlight(fieldname+'--content',{duration: 1, startcolor:"#2685AF"});
            update.push([fieldname+'--content',"#2685AF"]);
   				break;
   				case 'eval':
   					globaleval(p.firstChild.nodeValue);
   				break;
   				}
   			}
   			
   		});
   	});
 		}catch(e){
 			alert('expection ajaxsend on complete:'+e);
      //th.options.savedForm.form.submit();
 		}

    if(update.length > 0) update.each(function(v){
      scanner.process(v[0]);
      new Effect.Highlight(v[0],{duration: 1, startcolor:v[1]});
    });
 		
 		Ajax.savedForm = false;
 		if(Ajax.activeRequestCount <= oldActiveXHR && th.options.savedForm){
      var f = th.options.savedForm;
 			Form.enable(f.form);
 			var i = 0;
			Form.getInputs(f.form,'submit').each(function(s){ s.value = f.txt[i++]; });
		} //else alert(Ajax.activeRequestCount+'--'+ oldActiveXHR);
 
  },
  
  onException: function(th,e){
  	alert('Expection ajaxsend() : '+e);
  }
});

var add_wp_ajax_param = function (p){
  var classname = '<?php echo $_GET['class']; ?>';
  if(typeof(p) == 'object'){ //for prototype.js ver 1.5
    p.action = classname + '_xhr';
    p.cookie = encodeURIComponent(document.cookie);
  } else {
    p += '&action=' + classname + '_xhr&cookie=' + encodeURIComponent(document.cookie);
  }
  return p;
}

var xorax_wp_ajax_callback = function (func,args,reload_field){ // args is serialized and base64 encoded
	p = 'func_callback='+func;
	if(args) p += '&func_callback_args='+encodeURIComponent(args);
	if(reload_field) p += '&reload_field='+reload_field;
	p = add_wp_ajax_param(p);
	new Ajax.Request('admin-ajax.php', {
		method: 'post',
		parameters: p
		}
	);
}

var xorax_wp_ajax_reload_field = function (field){
  var p = 'reload_field='+field;
  p = add_wp_ajax_param(p);
  new Ajax.Request('admin-ajax.php', {
    method: 'post',
    parameters: p
    }
  );
}
  

Form.ajaxsend= function(form) {
	var pa = Form.serialize(form, true);
	pa = add_wp_ajax_param(pa);
	Form.disable(form);
	var formtxt = [];
	Form.getInputs(form,'submit').each(function(s){formtxt.push(s.value); s.value = "Loading..."});
	new Ajax.Request(
		'admin-ajax.php',
		{
			method: 'post',
			savedForm: {form: form, txt: formtxt},
			parameters: pa
		}
	);
	return false;
};

parsedUrl = parseUri(document.location.href);
scanner = {
  forms: function(target){
    if(target) target = $(target).getElementsBySelector('form');
    else target =  $A(document.getElementsByTagName('form'));
    
    target.each(function(v){
      //alert(Object.inspect(v));
      if(!v.onsubmit){
        v.onsubmit = function(){return scanner.formfunc(v);};
      }
      //Event.observe(v, 'submit',function(){return Form.ajaxsend(v);} );
      //v.onsubmit = function(){return false;}
    });
  },
  links: function(target){
    var t = (new Date()).getTime();
    if(target) target = $(target);
    else target =  $('xorax_wp_ajax_content');
    try{
      var fields = target.getElementsBySelector('.dbx-box[id] a');
    } catch(e){
      return false;
    }
    fields.each(function(v){
      if(!v.onclick){
        v.onclick = scanner.linkfunc;
        //v.style.color = "#FF0000";
       }
    });
    //alert((new Date()).getTime() - t);
  },
  parsedUrl: parseUri(document.location.href),
  getFieldQuery: function(ele){
    var fset = $(ele).up('.dbx-box');
    if(fset && fset.id){
      return 'reload_field='+fset.id;
    } else return false;
  },
  formfunc: function(form) { //applied to onsubmit event
    if(form.method != 'post'){
      var pag = '?'+form.serialize();
      var pa = {};
    } else {
      var pag = '';
      var pa = form.serialize(true);
    }
    if(!pa.field_action){
      alert('no:'+pa);
      var fs = form.up('.dbx-box');
      if(fs && fs.id) pa.reload_field = fs.id;
      else return true;
    }
    pa = add_wp_ajax_param(pa);
    Form.disable(form);
    var formtxt = [];
    Form.getInputs(form,'submit').each(function(s){formtxt.push(s.value); s.value = "Loading..."});
    new Ajax.Request(
      'admin-ajax.php'+pag,
      {
        method: 'post',
        savedForm: {form: form, txt: formtxt},
        parameters: pa
      }
    );
    return false;
  },
  linkfunc: function(){ //applied to onclick event
    var href = parseUri(this.href);
    if(href.authority == parsedUrl.authority &&
    	(href.path == parsedUrl.path || href.path.indexOf('wp-admin/admin-ajax.php') != -1) &&
    	href.queryKeys.page && href.queryKeys.page == parsedUrl.queryKeys.page
    ){
      var fq = scanner.getFieldQuery(this);
      if(fq){
        var pag = href.query;
        new Ajax.Request(
          'admin-ajax.php?'+pag,
          {
            method: 'post',
            parameters: add_wp_ajax_param(fq)
          }
        )
        return false;
      }
    } else alert('no good link');
    return true;
  },
  process: function(){
    this.forms();
    this.links();
  }
}

Event.observe(window, 'load', function(){
  scanner.process();
});

// parseUri : a good Steven Levithan function
// http://stevenlevithan.com/demo/parseUri/js.cfm
function parseUri(sourceUri){   
    var uriKeys = ["uri","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];   
    var uriParts = new RegExp("^(?:(?![^:@]+:[^:@/]*@)([^:/?#.]+):)?(?://)?((?:(([^:@]*):?([^:@]*))?@)?([^:/?#]*)(?::(\\d*))?)(((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[?#]|$)))*/?)?([^?#/]*))(?:\\?([^#]*))?(?:#(.*))?)").exec(sourceUri);   
    for(var i = 0, uri = {}; i < 14; i++){   
        uri[uriKeys[i]] = (uriParts[i] ? uriParts[i] : "");   
    }   
       
    // Parse the query (supports keys not followed by "=", and values which contain "=")   
    var q = (uri.query.length > 0 ? uri.query.split("&") : []);   
    for(i = 0, uri.queryKeys = {}; i < q.length; i++){   
        uri.queryKeys[q[i].match(/^[^=]+/)] = q[i].replace(/^[^=]+=?(.*)/, "$1");   
    }   
    return uri;   
}
